<template>
  <div class="app-container">
    <div v-show="!detailInfo.visible">
      <!-- <div class="width100"> -->
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
        </NewPageFilter>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-confirm>
            <el-button :disabled="!canConfirm" @click="confirm()"
              >确认
            </el-button>
          </template>
          <template v-slot:filter-excel>
            <el-button :disabled="groupFlag" @click="exportExcel()"
              >导出excel
            </el-button>
          </template>
          <template v-slot:filter-print>
            <el-button :disabled="groupFlag" @click="print()">打印 </el-button>
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <Group-select
            :options="groupSelectInfo.options"
            v-model:selections="groupSelectInfo.selections"
            @callback="groupSelect"
            @callbackVal="updateGroupSelections"
          ></Group-select>
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        v-if="groupFlag"
        class="groupFlag-container"
        :is-group-search="true"
        v-model:data="groupSelectInfo.data"
        :field-list="tableInfo.fieldList"
        :tab-index="false"
        :check-box="false"
        :pager="false"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :span-method="arraySpanMethod"
        :row-class-name="tableRowClassName"
        @exChange="exChange"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          {{ scope.row.orderNo }}
        </template>
      </table-container>
      <table-container
        v-else
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :summary="true"
        :summary-field-list="tableInfo.summaryFieldList"
        :tab-index="true"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :allSummary="true"
        :allSummaryData="allSummaryData"
        :handle="tableInfo.handle"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
        @pageInfo="pageInfo"
      >
        <template v-slot:col-orderNo="scope">
          <span
            v-if="$permission('consumeOrder:details')"
            class="slip-edit"
            @click="showDetail(scope.row)"
            >{{ scope.row.orderNo || '-' }}</span
          >
          <span v-else>{{ scope.row.orderNo || '-' }}</span>
        </template>
      </table-container>
      <!-- </div> -->
    </div>
    <consume-order-detail
      v-if="detailInfo.visible"
      :id="detailInfo.id"
      v-model:visible="detailInfo.visible"
      @returnBack="getList"
    />
    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      :field-list="tableInfo.fieldList"
      v-model:form-data="advancedSearchInfo.data"
      @callback="advancedSearchCallback"
    />
    <page-dialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </page-dialog>
  </div>
</template>
<script setup name="pendConfirmConsumeDetail">
import {
  batchConfirmPendConfirmConsumeDetail,
  getConsumeOrderDetailCustomizeListPage,
  getConsumeOrderDetailCustomizeListAll,
  getConsumeDetailsCustomizeGroups,
  excelDetailListPendConfirmConsumeDetail,
  printDetailListPendConfirmConsumeDetail,
  getConsumeOrderDetailCustomizeListSumAmount,
} from '@/api/stock.js'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { ElMessage } from 'element-plus'
import { fatchTemplateByCode } from '@/api/base'
import PageDialog from '@/components/PageDialog/index'
import _ from 'lodash'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const Tooltip = defineAsyncComponent(() => import('@/components/Tooltip/index'))
const AdvancedSearch = defineAsyncComponent(() =>
  import('@/components/AdvancedSearch/index')
)
const GroupSelect = defineAsyncComponent(() =>
  import('@/components/GroupSelect/index')
)

const ConsumeOrderDetail = defineAsyncComponent(() =>
  import('@/views/stock/consumeOrder/detail')
)
const TableContainer = defineAsyncComponent(() =>
  import('@/components/TableContainer/index')
)
const props = defineProps({
  visible: {
    type: Boolean,
  },
  query: {
    type: Object,
  },
  fromType: {
    type: [String, Number],
  },
})

//导出提示相关配置
const dialogInfo = reactive({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
let page = reactive({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
// 过滤相关配置
const groupSelectInfo = reactive({
  options: [],
  selections: [],
  data: [],
})
const filterInfo = reactive({
  sortArr: [],
  query: {
    sortString: '',
    copyQueryMap: {},
    groupMap: {},
    groups: [],
    queryMap: {
      depotAuth: {
        asTbName: 'consume_order',
        columnName: 'depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'depotAuth',
      },
      consignConfirmStatus: {
        queryType: 'IN',
        value: '1,2',
      },
      isConsignBusiness: {
        queryType: 'EQUALS',
        value: 1,
      },
    },
    queryParams: {
      confirmQtyGt: 0,
    },
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      value: 'confirm',
      type: 'slot',
      show: proxy.$permission('pendConfirmConsumeDetail:confirm'),
    },
    {
      value: 'excel',
      type: 'slot',
      show: proxy.$permission('pendConfirmConsumeDetail:exportExcel'),
    },
    {
      type: 'slot',
      value: 'print',
      show: proxy.$permission('pendConfirmConsumeDetail:print'),
    },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
    { value: 'supplierLatestSumAmount', formatter: proxy.$fn.TripartiteMethod },
    { value: 'chargeSumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  data: [],
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '确认',
        event: confirm,
        show: proxy.$permission('pendConfirmConsumeDetail:confirm'),
        ifRender: function (row) {
          return (
            row.consignConfirmStatus === 1 || row.consignConfirmStatus === 2
          )
        },
      },
    ],
  },
})
const allSummaryData = reactive({
  data: [],
  fieldList: [
    {
      label: '总金额',
      value: 'sumStockAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '最新价格总金额',
      value: 'supplierLatestSumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '计费总金额',
      value: 'chargeSumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
  ],
})
const detailInfo = reactive({
  visible: false,
  id: '',
})
const detailListInfo = reactive({
  visible: false,
})
const preferenceInfo = reactive({
  visible: false,
})
const advancedSearchInfo = reactive({
  visible: false,
  data: {},
})
const groupFlag = ref(false)
const clearType = ref(true)
const slipSelectRequest = ref(true)
const productionDateTime = ref('')
const validityDateTime = ref('')
const time = ref('')

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
const canConfirm = computed(() => {
  let row = proxy.$fn.deepClone(tableInfo.selections)
  if (row) {
    row.forEach((item) => {
      item._key = item.depotId + '&' + item.consumeDeptId
    })
    row = _.groupBy(row, '_key')
  }
  return (
    tableInfo.selections.length &&
    Object.keys(row).length &&
    Object.keys(row).length === 1 &&
    tableInfo.selections.filter((row) => row.consignConfirmStatus !== 1)
      .length === 0
  )
})

let obj = {
  price: {
    label: '单价',
    value: 'price',
    type: 'column',
    componentType: 'price',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('pendConfirmConsumeDetail:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    formatter: proxy.$fn.TripartiteMethod,
    componentType: 'price',
    type: 'column',
    permission: !proxy.$permission('pendConfirmConsumeDetail:price'),
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    componentType: 'price',
    permission: !proxy.$permission('pendConfirmConsumeDetail:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
    show: false,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
  commonName: {
    label: '通用名称',
    value: 'commonName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
})
getCustomize()

function _getIds(row) {
  let ids = []
  if (row && row.id) {
    ids = proxy.$fn.splitArr(row.groupConcatIds)
  } else {
    if (tableInfo.selections.length > 0) {
      tableInfo.selections.forEach((item) => {
        let arr = proxy.$fn.splitArr(item.groupConcatIds)
        ids = ids.concat(arr)
      })
    }
  }
  return ids
}
function confirm(row = undefined) {
  //确认
  const ids = _getIds(row)
  batchConfirmPendConfirmConsumeDetail(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function updateGroupSelections(arr) {
  filterInfo.query.groups = arr
  groupSelectInfo.selections = arr
  if (!arr.length) {
    filterInfo.query.groups = []
    filterInfo.query.groupMap = {}
    groupSelectInfo.data = []
    groupFlag.value = false
  }
}
function handleClose() {
  dialogInfo.visible = false
}
function pageInfo(obj) {
  page = obj
}
//导出excel
async function exportExcel() {
  dialogInfo.visible = true
  dialogInfo.type = 'excel'
  dialogInfo.msg = '请选择数据导出范围'
  dialogInfo.btList[1].label = '导出'
  dialogInfo.flag = true
}
function checkConfirm() {
  if (dialogInfo.type === 'excel') {
    exportExcelList()
  } else if (dialogInfo.type === 'print') {
    printList()
  }
  dialogInfo.visible = false
  dialogInfo.msg = ''
}
function exportExcelList() {
  let query = {
    customizeDto: filterInfo.query,
  }
  let params = {
    ...query,
    ...page,
    page: dialogInfo.flag,
  }
  excelDetailListPendConfirmConsumeDetail(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
async function print() {
  //打印
  dialogInfo.visible = true
  dialogInfo.type = 'print'
  dialogInfo.msg = '请选择当数据打印范围'
  dialogInfo.btList[1].label = '打印'
  dialogInfo.flag = true
}
function printList() {
  fatchTemplateByCode({
    resourceCode: 'pendConfirmConsumeDetail:print',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp, dialogInfo.flag)
    }
  })
}
function getPrintData(temp, flag) {
  let query = {
    customizeDto: filterInfo.query,
  }
  let params = {
    ...query,
    ...page,
    page: flag,
  }
  printDetailListPendConfirmConsumeDetail(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
function groupSelect(arr) {
  if (arr.length) {
    //点击分组
    groupFlag.value = true
    filterInfo.query.groups = arr
    groupSelectInfo.selections = arr
    getCustomizeGroupsList()
  } else {
    ElMessage.warning({
      message: '请选择分组条件！',
      showClose: true,
      duration: 3000,
    })
  }
}

async function getCustomizeGroupsList(len, param, expande) {
  //分组查询
  let params = {}
  if (len) {
    params = param
  } else {
    params = filterInfo.query
  }
  if (filterInfo.query.queryDtoList && filterInfo.query.queryDtoList.length) {
    params = proxy.$fn.deepClone(params)
    params.queryMap = {}
  }
  await getConsumeDetailsCustomizeGroups(params).then(async (res) => {
    if (res && res.success) {
      let data = res.data
      let newData = []
      if (len) {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ ...item, id: index + Math.random(), isColspan: true }],
          })
        })
        expande.children = newData
      } else {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ id: index + Math.random(), isColspan: true }],
          })
        })
        groupSelectInfo.data = newData
      }
    }
  })
}
function exChange(data, expandedRows) {
  //展开分组
  if (expandedRows) {
    let len = data.nextGroups.length
    if (len) {
      let params = {
        ...filterInfo.query,
        groups: data.nextGroups,
        groupMap: { ...data.query },
        queryMap: { ...filterInfo.query.queryMap, ...data.query },
      }
      getCustomizeGroupsList(len, params, data)
    } else {
      let params = {
        ...filterInfo.query,
        groups: [],
        groupMap: {},
        queryMap: { ...filterInfo.query.queryMap, ...data.query },
      }
      getConsumeOrderDetailCustomizeListAll(params).then(async (res) => {
        if (res && res.success) {
          let resData = res.data
          await resData.forEach((item, index) => {
            item.id = index + Math.random()
            item.isColspan = false
          })
          data.children = resData
        }
      })
    }
  } else {
    data.children = [{ id: Math.random(), isColspan: true }]
  }
}
function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.visible = true
}
async function advancedSearchCallback(obj) {
  let arr = [
    {
      fieldName: 'deptId',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'deptAuth',
    },
  ]
  filterInfo.query.queryMap = {}
  filterInfo.query.queryDtoList = [...obj.queryDtoList, ...arr]
  if (groupSelectInfo.selections.length > 0) {
    await getCustomizeGroupsList()
  } else {
    groupSelectInfo.data = []
    await getList()
  }
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  clearType.value = !clearType.value
}
// 获取列表
async function getList() {
  tableInfo.refresh = Math.random()
  // getSummary();
}
// 搜索
function search() {
  advancedSearchInfo.data = {}
  filterInfo.query.queryDtoList = []
  if (groupSelectInfo.selections.length > 0) {
    getCustomizeGroupsList()
  } else {
    groupSelectInfo.data = []
    tableInfo.initCurpage = Math.random()
    tableInfo.refresh = Math.random()
    // getSummary();
  }
}
function showDetail(row) {
  detailInfo.id = row.orderId
  detailInfo.visible = true
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  productionDateTime.value = []
  validityDateTime.value = []
  time.value = []
  advancedSearchInfo.data = {}
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'pendConfirmConsumeDetail-com.slip.spd.entity.vo.stock.ConsumeOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      let tableFieldInfo = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail,
        true
      )
      tableInfo.fieldList = tableFieldInfo.fieldList
      groupSelectInfo.options = tableFieldInfo.groupOption
      filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.query.queryMap,
      }
      filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap)
      if (props.fromType === 'route') {
        filterInfo.query.queryMap = {
          ...filterInfo.query.queryMap,
          ...props.query,
        }
      }
      filterInfo.searchList = searchInfo.searchList
      filterInfo.searchList.forEach((item) => {
        item.event = search
      })

      slipSelectRequest.value = _slipSelectRequest
      tableInfo.api = getConsumeOrderDetailCustomizeListPage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.sortArr)
    filterInfo.sortArr = arr
    filterInfo.query.sortString = arr.toString()
    getList()
  }
}
function tableRowClassName(row) {
  if (row.row.nextGroups) {
    return 'bg-color-EBEEF5'
  } else {
    return ''
  }
}
function arraySpanMethod({ row, column, rowIndex, columnIndex }) {
  if (row.nextGroups) {
    if (columnIndex === 0) {
      // return {
      //   rowspan: 1,
      //   colspan: tableInfo.fieldList.length
      // };
      return [1, tableInfo.fieldList.length + 1]
    }
  }
}
function productionDateChange(val) {
  if (val && val.length) {
    filterInfo.query.queryMap.productionDate.value = val[0] + ',' + val[1]
  } else {
    filterInfo.query.queryMap.productionDate.value = null
  }
}
function validityDateChange(val) {
  if (val && val.length) {
    filterInfo.query.queryMap.validityDate.value = val[0] + ',' + val[1]
  } else {
    filterInfo.query.queryMap.validityDate.value = null
  }
}
function getSummary() {
  getConsumeOrderDetailCustomizeListSumAmount(filterInfo.query).then((res) => {
    if (res && res.success) {
      if (res.data && res.data[0] !== null) {
        allSummaryData.data = [{ sumStockAmount: res.data },{ supplierLatestSumAmount: res.data },{ chargeSumAmount: res.data }]
      } else {
        allSummaryData.data = []
      }
    }
  })
}
</script>

<style scoped></style>
